import * as userService from '../model/userService'
import returnCode from '../common/returnCode'

export async function getUserList(ctx) {
    returnCode.SUCCESS.returnObject = await userService.getUserList()
    ctx.body = returnCode.SUCCESS
}

export async function getUser(ctx) {
    returnCode.SUCCESS.returnObject = await userService.getUserById(ctx.params.id)
    ctx.body = returnCode.SUCCESS
}

export async function checkUsername(ctx){
    if (await userService.checkUsername(ctx.request.body)) {
        returnCode.VALIDATEERROR.message = '用户名已存在'
        ctx.body = returnCode.VALIDATEERROR
    } else {
        ctx.body = returnCode.SUCCESS
    }
}

export async function insertUser(ctx) {
    if (await userService.checkUsername(ctx.request.body)) {
        returnCode.VALIDATEERROR.message = '用户名已存在'
        ctx.body = returnCode.VALIDATEERROR
    } else {
        let user = await userService.insertUser(ctx.request.body)
        returnCode.SUCCESS.returnObject = await userService.getUserById(user.id)
        ctx.body = returnCode.SUCCESS
    }
}

export async function updateUser(ctx) {
    if (await userService.checkUsername(ctx.request.body)) {
        returnCode.VALIDATEERROR.message = '用户名已存在'
        ctx.body = returnCode.VALIDATEERROR
    } else {
        await userService.updateUser(ctx.request.body)
        returnCode.SUCCESS.returnObject = await userService.getUserById(ctx.request.body.id)
        ctx.body = returnCode.SUCCESS
    }
}

export async function deleteUser(ctx) {
    await userService.deleteUser(ctx.params.id)
    ctx.body = returnCode.SUCCESS
}

export async function resetPassword(ctx) {
    await userService.resetPassword(ctx.params.id)
    ctx.body = returnCode.SUCCESS
}
